const cheerio = require('cheerio');
const curl = require('./curl');
const xlsx = require('./xlsx');
const moment = require('moment');

const get_world_data = function () {
  const url = "https://ncov.dxy.cn/ncovh5/view/pneumonia";

  return new Promise(function (resolve, reject) {
    curl.download(url, function (data) {
      if (data) {
        let window = {};
        let $ = cheerio.load(data);

        $('body>script:not([src])').each(function (index, ele) {
          let ele_data = ele.children[0].data;
          eval(ele_data);
        });

        const world_data_list = window.getListByCountryTypeService2;
        const china_data_list = window.getAreaStat;

        console.log('获取丁香医生数据成功！');

        let data_array = [world_data_list, china_data_list];
        resolve(data_array);
      } else {
        reject('获取丁香医生数据失败！')
      }
    })
  });
}

const get_data = async function (file) {
  let world_data = await get_world_data();

  let other_data_list = world_data[0];
  let china_data_list = world_data[1];

  let other_data_array = [
    ['大洲', '国家', '确诊', '疑似', '治愈', '死亡', '创建时间', '修改时间']
  ];
  other_data_list.forEach(ele => {
    let createTime = moment(ele.createTime).format('YYYY-MM-DD HH:mm:ss');
    let modifyTime = moment(ele.modifyTime).format('YYYY-MM-DD HH:mm:ss');

    other_data_array.push([ele.continents, ele.provinceName,
      ele.confirmedCount, ele.suspectedCount, ele.curedCount, ele.deadCount, createTime, modifyTime
    ]);
  });

  let china_province_data_array = [
    ['省份编码', '省份名称', '确诊', '疑似', '治愈', '死亡']
  ];
  let china_city_data_array = [
    ['省份编码', '省份名称', '地市编码', '地市名称', '确诊', '疑似', '治愈', '死亡']
  ];

  china_data_list.forEach(province => {
    china_province_data_array.push([province.locationId, province.provinceName,
      province.confirmedCount, province.suspectedCount, province.curedCount, province.deadCount
    ]);

    province.cities.forEach(ele => {
      china_city_data_array.push([province.locationId, province.provinceName, ele.locationId, ele.cityName,
        ele.confirmedCount, ele.suspectedCount, ele.curedCount, ele.deadCount
      ]);
    });
  });

  let new_file = new xlsx.Xlsx(file);

  new_file.add({
    name: '全球',
    data: other_data_array
  });

  new_file.add({
    name: '省份',
    data: china_province_data_array
  });

  new_file.add({
    name: '地市',
    data: china_city_data_array
  });

  await new_file.writeFileSync();
}

exports.get_data = get_data;